package com.kun.video.util;

import cn.hutool.core.util.StrUtil;
import com.kun.video.AbstractApplication;
import javafx.scene.layout.Region;
import javafx.scene.shape.SVGPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.io.StringReader;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 资源管理器
 *
 * @author gzc
 * @since 2025/3/15
 **/
public class ResourceManager {
    private static final Logger log = LoggerFactory.getLogger(ResourceManager.class);

    private static final Map<String, Region> SVG_MAP = new ConcurrentHashMap<>(16);

    public static String loadSvgContent(String svgPath) {
        if (StrUtil.isBlank(svgPath)) {
            return "";
        }
        try {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            //禁止DTD验证,防止网络阻塞
            builder.setEntityResolver((publicId, systemId) -> new InputSource(new StringReader("")));
            // 读取svg xml数据
            InputStream resourceAsStream = AbstractApplication.class.getResourceAsStream(svgPath);
            // 转换成document对象
            Document document = builder.parse(resourceAsStream);
            if (document == null) {
                return "";
            }
            Node node = document.getElementsByTagName("path").item(0);
            if (node == null) {
                return "";
            }
            return node.getAttributes().getNamedItem("d").getNodeValue();
        } catch (Exception e) {
            log.error("读取svg【" + svgPath + "】发生异常->", e);
        }
        return "";
    }

    public static Region loadSvgRegion(String svgPath, String style) {
        if (StrUtil.isBlank(svgPath)) {
            return null;
        }
//        if (SVG_MAP.containsKey(svgPath)) {
//            final Region region = SVG_MAP.get(svgPath);
//            return region;
//        }
        SVGPath svgObj = new SVGPath();
        svgObj.setContent(loadSvgContent(svgPath));
        Region region = new Region();
        region.setShape(svgObj);
        region.setStyle(StrUtil.isBlank(style) ? "-fx-background-color: #67c23a;-fx-pref-width: 18;-fx-pref-height: 18" : style);
//        SVG_MAP.put(svgPath, region);
        return region;
    }

}
